package com.xkdx.guangguang.util;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

public class AESUtil {
	private static final int AES_TYPE = 128; // 128位密钥

	// /**
	// * 测试代码
	// * @param args
	// */
	// public static void main(String[] args) {
	// String content = "xingkong518\n\n\n\n\n";
	// //String password = "xiangevfiveydtsg201314";
	static String password = "xiangevfiveydtsg";

	//
	// System.out.println("待加密字符串：" + content+"代加密字符串的长度"+content.length());
	// System.out.println("密码：" + password);
	//
	// String encryptResultStr = aesEncrypt(content, password);
	// System.out.println("加密后："+encryptResultStr);
	//
	// encryptResultStr = aesDecrypt(encryptResultStr, password);
	// System.out.println("解密后："+encryptResultStr);
	// }

	/**
	 * 加密
	 * 
	 * @param content
	 *            待加密串
	 * @param password
	 *            密码
	 * @return
	 */
	public static String aesEncrypt(String content) {
		byte[] bytes = encrypt(content, password);
		return convertBytesToString(bytes);
	}

	/**
	 * 解密
	 * 
	 * @param content
	 *            密文
	 * @param password
	 *            密码
	 * @return
	 */
	public static String aesDecrypt(String content) {
		byte[] decryptFrom = parseHexStr2Byte(content);
		byte[] bytes = decrypt(decryptFrom);
		return new String(bytes);
	}

	/**
	 * 字符数组转字符串 - 加密后是2进制
	 * 
	 * @param bytes
	 * @return
	 */
	private static String convertBytesToString(byte[] bytes) {
		String encryptResultStr = parseByte2HexStr(bytes);
		return encryptResultStr;
	}

	/**
	 * 加密
	 * 
	 * @param content
	 *            需要加密的内容
	 * @param password
	 *            加密密码
	 * @return
	 */
	public static byte[] encrypt(String content, String password) {
		try {
			/**
			 * 创建AES加密器
			 */
			Cipher cipher = initCipher(Cipher.ENCRYPT_MODE);

			/**
			 * 将需要加密的字符串转换成utf8的字节数组
			 */
			byte[] byteContent = content.getBytes("GBK");

			/**
			 * 使用加密器加密
			 */
			byte[] result = cipher.doFinal(byteContent);

			return result;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 解密
	 * 
	 * @param content
	 *            待解密内容
	 * @param password
	 *            解密密钥
	 * @return
	 */
	public static byte[] decrypt(byte[] content) {
		try {
			/**
			 * 创建AES解密器
			 */
			Cipher cipher = initCipher(Cipher.DECRYPT_MODE);

			/**
			 * 解密
			 */
			byte[] result = cipher.doFinal(content);

			return result;
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 初始化
	 * 
	 * @param type
	 *            加密器/解密器
	 * @param password
	 *            密码
	 * @return
	 */
	private static Cipher initCipher(int type) {

		try {
			/**
			 * 密钥生成器
			 */
			// KeyGenerator kgen = KeyGenerator.getInstance("AES");
			/**
			 * 使用password 来生成 128位的加密密钥
			 */
			// kgen.init(AES_TYPE, new SecureRandom(password.getBytes()));

			/**
			 * 获取私密
			 */
			// SecretKey secretKey = kgen.generateKey();

			/**
			 * 私密数组
			 */
			// byte[] enCodeFormat = secretKey.getEncoded();
			byte[] enCodeFormat = password.getBytes();

			/**
			 * 生成key
			 */
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");

			/**
			 * 创建AES加密器
			 */
			// Cipher cipher = Cipher.getInstance("AES");
			Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");

			/**
			 * 初始化加密器
			 */
			cipher.init(type, key);

			return cipher;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 将二进制转换成16进制
	 * 
	 * @param buf
	 * @return
	 */
	public static String parseByte2HexStr(byte buf[]) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < buf.length; i++) {
			String hex = Integer.toHexString(buf[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}

	/**
	 * 将16进制转换为二进制
	 * 
	 * @param hexStr
	 * @return
	 */
	public static byte[] parseHexStr2Byte(String hexStr) {
		if (hexStr.length() < 1)
			return null;
		byte[] result = new byte[hexStr.length() / 2];
		for (int i = 0; i < hexStr.length() / 2; i++) {
			int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
			int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
			result[i] = (byte) (high * 16 + low);
		}
		return result;
	}

}
